package com.gzbugu.bugusys.service.impl;

import java.io.File;
import java.io.IOException;

import javax.annotation.Resource;

import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.gzbugu.bugusys.dao.IBaseDAO;
import com.gzbugu.bugusys.service.IAddContractServiceService;
import com.gzbugu.bugusys.util.RandomChars;
import com.gzbugu.bugusys.vo.ContractService;

/**
 * @author Bokchoy
 * 增加劳务合同Service
 */
@Service
@Transactional
public class AddContractServiceService implements IAddContractServiceService {
	
	private String location = "\\upload\\contract\\";
	@Resource(name="baseDAO")
	private IBaseDAO baseDAO;
	
	/* (non-Javadoc)
	 * @see com.gzbugu.bugusys.service.impl.IContractServiceService#save(com.gzbugu.bugusys.vo.ContractService, java.io.File, java.lang.String)
	 */
	public boolean save(ContractService instance,File upload,String fileType) {
		boolean flag = false;
		String url = uploadFile(upload,fileType);
		instance.setUrl(url);
		baseDAO.save(instance);
		return flag;
	}
	
	private String uploadFile(File upload,String fileType) {
		System.out.println(upload.getPath());
		String flag="";
		String realLocation = ServletActionContext.getServletContext().getRealPath(
				location);
		String castUrl = realLocation+File.separator;
		String targetName = RandomChars.randomChars(21)+fileType;
		String url = castUrl.substring(castUrl.lastIndexOf(location
				.replaceAll("\\\\", "/"))+1);
		File target = new File(url,targetName);
		try {
			FileUtils.copyFile(upload, target);
			flag = (location + target.getName()).substring(1);
		} catch (IOException e) {
			System.out.println("File copy error");
		}
		return flag;
	}
}
